/*
 * Copyright 2011-2020 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0.
 * See `LICENSE` in the project root for license information.
 */

package me.ijleex.mgmt.system.auth.service.impl;

import java.util.List;

import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import me.ijleex.mgmt.system.auth.model.JwtUser;
import me.ijleex.mgmt.system.role.entity.Role;
import me.ijleex.mgmt.system.role.mapper.RoleMapper;
import me.ijleex.mgmt.system.user.entity.User;
import me.ijleex.mgmt.system.user.mapper.UserMapper;

/**
 * JwtUserDetailsService.
 *
 * @author liym
 * @since 2020-08-09 09:37 新建
 */
@Service
public class JwtUserServiceImpl implements UserDetailsService {

    private final UserMapper userMapper;
    private final RoleMapper roleMapper;

    public JwtUserServiceImpl(UserMapper userMapper, RoleMapper roleMapper) {
        this.userMapper = userMapper;
        this.roleMapper = roleMapper;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = this.userMapper.selectByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户名或密码不正确！");
        }
        Integer state = user.getState();
        if (state == null || state != 0) {
            return new JwtUser(username, false);
        }
        Long userId = user.getId();
        List<Role> roleList = this.roleMapper.selectByUserId(userId);
        return new JwtUser(userId, username, user.getPassword(), roleList);
    }

}
